package kyssion.leetcode.num101_150;

import kyssion.leetcode.util.TreeNode;

public class code124_二叉树中的最大路径和 {
    public static void main(String[] args) {
        TreeNode treeNode = TreeNode.create(
                new int[]{
                        -3
                }
        );

        System.out.println( new code124_二叉树中的最大路径和().maxPathSum(treeNode));
    }

    int max = Integer.MIN_VALUE;

    public int maxPathSum(TreeNode root) {
        if (root == null) {
            return 0;
        }
        max = Integer.MIN_VALUE;
        ans(root);
        return max;
    }

    private int ans(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int right = ans(root.right);
        int left = ans(root.left);
        max = Math.max(max, right + left + root.val);
        left = left + root.val;
        right = right + root.val;
        int item = Math.max(root.val, Math.max(left, right));
        max = Math.max(item, max);
        return item;
    }
}
